package com.shihang.crm.web.action;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import com.shihang.crm.bean.Customer;
import com.shihang.crm.service.CustomerService;
import com.shihang.crm.utils.PageBean;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;

import java.io.File;

public class CustomAction extends ActionSupport implements ModelDriven<Customer> {
    private Customer customer = new Customer();

    private CustomerService cs;

    //当前页数
    private int currentPage;
    //每页显示条数
    private int pageSize;

    private File photo;


    public String list() throws Exception{
        //封装离线查询对象
        DetachedCriteria dc = DetachedCriteria.forClass(Customer.class);
        if(StringUtils.isNotBlank(customer.getCust_name())){
            dc.add(Restrictions.like("cust_name","%"+customer.getCust_name()+"%"));
        }

        //1.调用Service查询分页数据（PageBean）
        PageBean pb = cs.getPageBean(dc,currentPage,pageSize);
        //2.将PageBean放入request域，转发到列表页面显示
        ActionContext.getContext().put("pageBean",pb);
        return "list";
    }


    public String toEdit() throws Exception{
        //调用service根据id获得customer对象
        Customer c = cs.getById(customer);
        ActionContext.getContext().put("customer",c);
        return "edit";
    }

    public String add() throws Exception {
        //1.调用service 保存customer对象
        cs.saveOrUpDate(customer);
        //2.重定向到客户列表
        /*System.out.println("fffffffffffff");
        String path = photo.getAbsolutePath();
        photo.renameTo(new File("E:/pic/up.png"));
        System.out.println(path);*/
        //System.out.println(photo.getAbsolutePath());
        return "toList";
    }

    void test(){

    }


    public CustomerService getCs() {
        return cs;
    }

    public void setCs(CustomerService cs) {
        this.cs = cs;
    }

    public int getCurrentPage() {
        return currentPage;
    }

    public void setCurrentPage(int currentPage) {
        this.currentPage = currentPage;
    }

    public int getPageSize() {
        return pageSize;
    }

    public void setPageSize(int pageSize) {
        this.pageSize = pageSize;
    }

    public File getPhoto() {
        return photo;
    }

    public void setPhoto(File photo) {
        this.photo = photo;
    }

    @Override
    public Customer getModel() {
        return customer;
    }
}
